<?php

namespace App\Services\RewardGoldPrize;

use App\Models\User;
use App\Models\GoldRecord;

class RewardFirstParent
{
	protected User $user;

	protected ?User $parent = null;

	protected GoldRecord $goldRecord;

	protected function setParams(GoldRecord $record)
	{
		$this->user = $record->user;
		$this->parent = $this->user->parent;
		$this->goldRecord = $record;
	}

	protected function canParentReceivePrize(): bool
	{
		$parent = $this->parent;
		$record = $this->goldRecord;

		if (! $parent) {
			return false;
		} elseif ($record->isRewarded()) {
			return false;
		} elseif (! $this->wasParentInSameRound()) {
            return false;
        } else {
            return true;
        }
	}

    protected function wasParentInSameRound(): bool
    {
        return $this->parent->goldRecords()
            ->where('gold_round_id', $this->goldRecord->gold_round_id)
            ->whereDate('created_at', $this->goldRecord->created_at)
            ->whereNotNull('paid_at')
            ->exists();
    }

	protected function settle()
	{
		$parent = $this->parent;
		$record = $this->goldRecord;
		$money = $parent->stormDirectPrizeMoneyToday($record);

        if ($money->isGreaterThan(0)) {
            $data = ['gold_record_id' => $record->id];
            account_coins($parent)->plusGoldRecordDirectPrize($money, $data);
            if ($parent->gold_subsidies > 0
                and $money <= $parent->gold_subsidies) {
                account_coins($parent)->plusUnlockedSubsidise($money, $data);
                account_subsidies($parent)->minusUnlockedSubsidise($money, $data);
            }
        }
	}

	public function reward(GoldRecord $record): bool
	{
		$this->setParams($record);

		if ($this->canParentReceivePrize()) {
			$this->settle();
		}

		return true;
	}
}
